package com.example.eeuse.listener;

import cn.hutool.core.bean.BeanUtil;
 import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.example.eeuse.mapper.SubsidyRecordDataMapper;
import com.example.eeuse.model.BankAccount;
import com.example.eeuse.model.SubsidyRecordData;
import com.example.eeuse.model.vo.SubsidyRecordDataVo;
import lombok.extern.slf4j.Slf4j;

 import java.util.List;
import java.util.UUID;

@Slf4j
public class SubsidyMesDataVoListenter implements ReadListener<SubsidyRecordDataVo> {


    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 30000;

    /**
     * 缓存的数据
     */
    private List<SubsidyRecordData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private SubsidyRecordDataMapper mesDataMapper;

    public SubsidyMesDataVoListenter( SubsidyRecordDataMapper mesDataMapper) {
        this.mesDataMapper =mesDataMapper;
    }

    @Override
    public void invoke(SubsidyRecordDataVo subsidyMesDataVo, AnalysisContext analysisContext) {
        SubsidyRecordData subsidyMesData = BeanUtil.toBean(subsidyMesDataVo, SubsidyRecordData.class);
        cachedDataList.add(subsidyMesData);
        //log.info(JSON.toJSONString(subsidyMesData));
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            saveToExcel(cachedDataList);
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        cachedDataList.forEach(x->{
            x.setId(IdUtil.simpleUUID());
            x.setCreateCode(IdUtil.nanoId());
            x.setCreateTime(DateUtil.date());
        });
        mesDataMapper.insertBatch(cachedDataList);
        log.info("存储数据库成功！");
    }

    private void saveToExcel(List<SubsidyRecordData> dataList){
        String filename = "E:\\xls_sp\\btjl_" + UUID.randomUUID().toString() + ".xlsx";
        log.info("{}条数据，保存到文件 {}！", cachedDataList.size(),filename);
        EasyExcel.write(filename, SubsidyRecordData.class).sheet(0).doWrite(dataList);
    }
}
